import pygame
from pygame.sprite import Sprite
import queue
from web import mainThread
import time, math

# 定义窗口大小
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 800
# 定义预设颜色
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
BLUE = pygame.Color(0, 0, 255)
# 定义系统参数
cfg = {"menu": None, "input": None}
tcp = {"recv": queue.Queue(), "send": queue.Queue()}


# ----------------------------------------------------
class Baseitem(Sprite):
    def __init__(self, color, width, height):
        pygame.sprite.Sprite.__init__(self)


# -----------------------------------------------------
class Tank(Baseitem):
    """坦克类"""

    def __init__(self, left, top):
        pass


class Bullet(Baseitem):
    """子弹类"""

    def __init__(self, tank):
        pass


class Explode:
    """爆炸类"""

    def __init__(self, tank):
        pass


# -------------------------------------------------------
class MyTank(Tank):
    """我方坦克"""

    def __init__(self, left, top):
        super(MyTank, self).__init__(left, top)
        self.live = True
        self.image = pygame.image.load("img/p1tankR.gif")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top
        self.direction = 0  # pygame.transform.rotate  # 当前方向
        self.speed = 5  # 移动速度
        self.stop = True  # 移动状态
        self.base_image = self.image
        print("当前方向:", self.direction)

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def move(self, direction):
        print("移动角度:", direction)
        x, y = self.rect.left, self.rect.top
        dx = self.speed * math.cos(math.radians(direction))
        dy = self.speed * math.sin(math.radians(direction))
        print(dx, dy)
        if 90 <= direction <= 180:
            print("象限1")
            x += dx
            y -= dy
        elif 0 <= direction <= 90:
            print("象限2")
            x += dx
            y -= dy
        elif 190 <= direction <= 270:
            print("象限3")
            x += dx
            y -= dy
        elif 270 <= direction <= 360:
            print("象限4")
            x += dx
            y -= dy
        else:
            pass
        print(x, y)
        if x < 0:
            x = 0
        if x > SCREEN_WIDTH - self.rect.width:
            x = SCREEN_WIDTH - self.rect.width
        if y < 0:
            y = 0
        if y > SCREEN_HEIGHT - self.rect.height:
            y = SCREEN_HEIGHT - self.rect.height
        self.rect.left, self.rect.top = x, y

    def rotate(self):
        """旋转"""
        direction = self.direction
        if direction > 359:
            self.direction = direction - 360
        if direction < 0:
            self.direction = direction + 360
        print(direction)
        self.image = pygame.transform.rotate(self.base_image, self.direction)
        self.rect = self.image.get_rect(
            center=self.rect.center
        )  # center=self.rect.center


class EnemyTank(Tank):
    """敌方坦克"""

    def __init__(self, left, top):
        super(EnemyTank, self).__init__(left, top)
        self.live = True
        self.image = pygame.image.load("img/enemy1R.gif")
        self.rect = self.image.get_rect()  # 根据图片获取区域
        self.rect.left, self.rect.top = left, top
        self.direction = 0  # pygame.transform.rotate  # 当前方向
        self.speed = 5  # 移动速度
        self.stop = True  # 移动状态
        self.base_image = self.image
        self.guid = ""
        print("当前方向:", self.direction)

    def displayTank(self):
        # 调用blit展示
        MainGame.window.blit(self.image, self.rect)

    def move(self, direction):
        print("移动角度:", direction)
        x, y = self.rect.left, self.rect.top
        dx = self.speed * math.cos(math.radians(direction))
        dy = self.speed * math.sin(math.radians(direction))
        print(dx, dy)
        if 90 <= direction <= 180:
            print("象限1")
            x += dx
            y -= dy
        elif 0 <= direction <= 90:
            print("象限2")
            x += dx
            y -= dy
        elif 190 <= direction <= 270:
            print("象限3")
            x += dx
            y -= dy
        elif 270 <= direction <= 360:
            print("象限4")
            x += dx
            y -= dy
        else:
            pass
        print(x, y)
        if x < 0:
            x = 0
        if x > SCREEN_WIDTH - self.rect.width:
            x = SCREEN_WIDTH - self.rect.width
        if y < 0:
            y = 0
        if y > SCREEN_HEIGHT - self.rect.height:
            y = SCREEN_HEIGHT - self.rect.height
        self.rect.left, self.rect.top = x, y

    def rotate(self):
        """旋转"""
        direction = self.direction
        if direction > 359:
            self.direction = direction - 360
        if direction < 0:
            self.direction = direction + 360
        print(direction)
        self.image = pygame.transform.rotate(self.base_image, self.direction)
        self.rect = self.image.get_rect(
            center=self.rect.center
        )  # center=self.rect.center


class Music:
    def __init__(self, filename):
        self.filename = filename
        pygame.mixer.init()
        pygame.mixer.music.load(self.filename)  # 加载音乐

    # 音乐播放
    def play(self):
        pygame.mixer.music.play()


# ------------------------------------------------------
class MainGame:
    window = None
    my_tank = None  # 自己
    enemyTankList = []  # 敌方坦克列表

    def __init__(self):
        self.isRun = True
        self.alert = False

    def stop(self):
        self.isRun = False

    def startGame(self):
        pygame.display.init()  # 加载主窗口
        MainGame.window = pygame.display.set_mode(
            [SCREEN_WIDTH, SCREEN_HEIGHT]
        )  # 设置窗口大小并显示
        # 窗口标题设置
        pygame.display.set_caption("坦克大作战")
        # 关闭输入法
        pygame.key.stop_text_input()
        # 初始化自己
        self.createMytank()
        # cfg["menu"] = [
        #     "选择战场:",
        #     "0 合作模式",
        #     "1 对抗战场一",
        #     "2 对抗战场二",
        #     "3 对抗战场三",
        #     "4 对抗战场四",
        #     "5 对抗战场五",
        #     "6 对抗战场六 ",
        #     "7 对抗战场七",
        #     "8 对抗战场八",
        # ]
        # cfg["input"] = [
        #     pygame.K_0,
        #     pygame.K_1,
        #     pygame.K_2,
        #     pygame.K_3,
        #     pygame.K_4,
        #     pygame.K_5,
        #     pygame.K_6,
        #     pygame.K_7,
        #     pygame.K_8,
        # ]
        while self.isRun:
            time.sleep(0.02)
            # 颜色填充
            MainGame.window.fill(BLACK)
            # 获取事件
            self.getEvent()
            # 绘制文字
            # MainGame.window.blit(
            #     self.getTextSuface("敌方坦克剩余数量%d" % 10), (10, 10)
            # )
            # 绘制菜单文字
            if cfg.get("menu"):
                msg = self.messageShow(cfg.get("menu"))
                for surface, pos in msg:
                    MainGame.window.blit(surface, pos)
            # 更新自己
            if MainGame.my_tank and MainGame.my_tank.live:
                MainGame.my_tank.displayTank()  # 展示我方坦克
            else:
                del MainGame.my_tank  # 删除我方坦克
                MainGame.my_tank = None
            # 更新敌方
            for enemyTank in MainGame.enemyTankList:
                if enemyTank.live:  # 判断敌方坦克状态
                    enemyTank.displayTank()
                else:
                    MainGame.enemyTankList.remove(enemyTank)
            # 检测网络消息
            if not tcp["recv"].empty():
                msg = tcp["recv"].get()
                print(type(msg), msg)
                if msg.get("act") == "enter" and msg.get("code") == 200:
                    tcp["send"].put({"act": "group", "guid": thread1.guid, "data": 2})
                if msg.get("act") == "group" and msg.get("code") == 200:
                    cfg["menu"] = ["请准备", "1 准备就绪"]
                    cfg["input"] = [
                        pygame.K_1,
                    ]
                if msg.get("act") == "move_start" or msg.get("act") == "move_end":
                    if not msg.get("guid") == thread1.guid:
                        EnemyTank = self.findEnemyTank(
                            msg.get("guid"), msg.get("c_x"), msg.get("c_y")
                        )
                        EnemyTank.rect.left = msg.get("c_x")
                        EnemyTank.rect.top = msg.get("c_y")
                        EnemyTank.speed = msg.get("speed")
                        EnemyTank.direction = msg.get("c_z")
                        EnemyTank.move(msg.get("t_z"))
                        EnemyTank.rotate()

            # 更新视图
            pygame.display.update()

    def endGame(self):
        """游戏结束"""
        self.stop()
        # exit()  # 退出游戏

    def getTextSuface(self, text):
        """文字显示"""
        pygame.font.init()  # 字体初始化
        font = pygame.font.SysFont("kaiti", 16)
        # 绘制文字信息
        textSurface = font.render(text, True, GREEN)
        return textSurface

    def messageShow(self, textlist=[]):
        """显示文本"""
        pygame.font.init()
        font = pygame.font.SysFont("SimSun", 22)
        text_surfaces = [font.render(line, True, (0, 255, 0)) for line in textlist]
        text_positions = [
            (5, 400 + i * (text_surfaces[0].get_height() + 5))
            for i, _ in enumerate(textlist)
        ]
        return zip(text_surfaces, text_positions)

    def createMytank(self):
        """创建自己"""
        MainGame.my_tank = MyTank(350, 300)
        music = Music("img/start.wav")  # 创建音乐对象
        music.play()  # 播放音乐

    def createEnemyTank(self, guid, x, y):
        """创建敌方"""
        enemy = EnemyTank(x, y)
        enemy.guid = guid
        MainGame.enemyTankList.append(enemy)
        return enemy

    def findEnemyTank(self, guid, x, y):
        """查找敌方"""
        for i in MainGame.enemyTankList:
            if i.guid == guid:
                return i
        return self.createEnemyTank(guid, x, y)

    def getEvent(self):
        """获取所有事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出游戏
                self.endGame()
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_1:
                    print(0 - (48 - event.key))
                    tcp["send"].put({"act": "ready", "guid": thread1.guid, "data": ""})
                    cfg["menu"] = None
                    cfg["input"] = None
                elif event.key in [pygame.K_w, pygame.K_s]:
                    self.reportPosition(act="move_end")
                    self.alert = False
            if event.type == pygame.KEYDOWN:
                if event.key in [pygame.K_w, pygame.K_s]:
                    self.alert = True
                    self.reportPosition()
        # 按住按键
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            direction = MainGame.my_tank.direction
            MainGame.my_tank.move(direction)
            # self.reportPosition()
        if keys[pygame.K_s]:
            direction = MainGame.my_tank.direction + 180
            if direction > 359:
                direction = direction - 360
            MainGame.my_tank.move(direction)
            # self.reportPosition()
        if keys[pygame.K_a]:
            MainGame.my_tank.direction += 10
            MainGame.my_tank.rotate()
        if keys[pygame.K_d]:
            MainGame.my_tank.direction -= 10
            MainGame.my_tank.rotate()

    def reportPosition(self, act="move_start"):
        """报告位置"""
        d = {
            "act": act,
            "guid": thread1.guid,
            "id": 2,
            "c_x": MainGame.my_tank.rect.left,
            "c_y": MainGame.my_tank.rect.top,
            "c_z": MainGame.my_tank.direction,
            "t_x": 0.0,  # target
            "t_y": 0.0,
            "t_z": 1.0,
            "speed": MainGame.my_tank.speed,  # move_speed
            # "forward": 1
        }
        tcp["send"].put(d)


if __name__ == "__main__":
    print("hello")
    # 网路线程
    thread1 = mainThread(tcp)
    thread1.start()
    thread2 = MainGame()
    thread2.startGame()
    thread1.stop()
    thread1.join()
    print("bye")
